package com.bbs.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbs.core.dao.MessageDao;
import com.bbs.core.dao.TopicDao;
import com.bbs.core.model.Message;
import com.bbs.core.service.MessageService;

@Service(value = "messageService")
public class MessageServiceImpl implements MessageService{
	
	@Autowired
	MessageDao messageDao;
	
	@Autowired
	TopicDao topicDao;

	@Override
	public void updateMyTopic(int msgId, byte status) {
		Message msg = new Message();
		msg.setStatus(status);
		msg.setId(msgId);
		messageDao.updateByPrimaryKeySelective(msg);
		
	}
	
	@Override
	public Message makeOneBbsMessage(int userId,int topicId,byte status){
		Message msg = new Message();
		msg.setUserId(userId);
		msg.setTopicId(topicId);
		List<Message> list = messageDao.selectByUserIdAndTopicId(msg);
		if(list.isEmpty()){
			msg.setStatus(status);
			messageDao.insert(msg);
			return msg;
		}else{
			msg =  list.get(0);
			if(msg.getStatus()!=status){
				msg.setStatus(status);
				messageDao.updateByPrimaryKeySelective(msg);
			}
			return msg;
		}
			
	}
	
	@Override
//	@CacheEvict(cacheNames={"MY-MESSAGE","MY-MESSAGE-COUNT"}, allEntries=true)
	public void notifyParticipant(int topicId,int ownerId){
		List<Integer> userIds = topicDao.selectUserIdsByPrimaryKey(topicId);
		for(Integer userId:userIds){
			if(userId==ownerId){
				continue;
			}
			//TODO,以后改成批处理,但存在insert&update问题
			makeOneBbsMessage(userId,topicId,(byte) 1);
		}
	}

}
